package com.han.fu.api.common.handle;

import com.alibaba.fastjson.JSON;
import com.han.fu.api.common.model.ResponseVo;
import com.han.fu.api.common.enums.SecurityEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author star
 * @version 1.0.0
 * @Description: 认证失败
 * @date 2020/7/20
 */
@Component
@Slf4j
public class FailAuthEntryPointHandle implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //验证为未登陆状态会进入此方法，认证错误
        log.warn("{}-认证失败：{}", request.getServletPath(), e.getMessage());
        response.setStatus(SecurityEnum.AUTH_FAIL.getCode());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        ResponseVo<String> result = new ResponseVo<>();
        SecurityEnum.setResponseVo(result, SecurityEnum.AUTH_FAIL);
        String body = JSON.toJSONString(result);
        printWriter.write(body);
        printWriter.flush();
    }
}
